package com.bw.servlet;

import com.alibaba.fastjson.JSON;
import com.bw.pojo.User;
import com.bw.util.JDBC;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/***************************
 FileAction:

 CreateTime:2022-08-19 15:46
 Author:Aaking-aline
 ****************************/
@WebServlet("/GetUserServlet")
public class GetUserServlet extends HttpServlet {
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	@SneakyThrows
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");

		Connection conn = JDBC.getConnecton();
		PreparedStatement ps = conn.prepareStatement("select * from user where username = ?");

		ps.setObject(1,username);
		ResultSet rs = ps.executeQuery();

		List<User> list = new ArrayList<>();
		while(rs.next()){
			User user = new User(rs.getInt(1), rs.getString(2), rs.getString(3));
			list.add(user);
		}

		String json = JSON.toJSONString(list);
		response.getWriter().write(json);
	}
}
